<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--部门流程数据-->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item el-form-item label="流程名称" prop="flowName">
            <el-input
              v-model="queryParams.flowName"
              placeholder="请输入流程名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="用户名" prop="userName">
            <el-input
              v-model="queryParams.userName"
              placeholder="请输入创建流程的用户名"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="流程标识" prop="flowIden">
            <el-input
              v-model="queryParams.flowIden"
              placeholder="请输入流程的唯一标识"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item label="流程状态" prop="flowStatus">
            <el-select
              v-model="queryParams.flowStatus"
              placeholder="请选择流程状态"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            >
              <el-option
                v-for="item in flowStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="showFormList"
              >新增
            </el-button>
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="flowList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="流程名"
            align="center"
            key="flowInfo.name"
            prop="flowInfo.name"
            v-if="columns[0].visible"
          />
          <el-table-column
            label="用户名称"
            align="center"
            key="userName"
            prop="userName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="用户昵称"
            align="center"
            key="nickName"
            prop="nickName"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="部门"
            align="center"
            key="deptName"
            prop="deptName"
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="流程标识"
            align="center"
            key="flowInfo.flowIden"
            prop="flowInfo.flowIden"
            v-if="columns[4].visible"
            width="120"
          />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            v-if="columns[5].visible"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.flowInfo.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            align="center"
            prop="flowInfo.status"
            v-if="columns[6].visible"
            width="160"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.flowInfo.status"
                :active-value="true"
                :inactive-value="false"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-link
                :underline="false"
                icon="el-icon-view"
                @click="queryFlow(scope.row.id)"
                >查看</el-link
              >&nbsp;
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                title="确定要删除表单吗？"
                @confirm="deleteFlow(scope.row.id)"
              >
                <el-link
                  slot="reference"
                  class="el-icon-delete-solid"
                  :underline="false"
                  >删除
                </el-link>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNo"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 新建流程对话框 -->
    <el-dialog
      title="新建流程"
      :visible.sync="flowDialogVis"
      width="600px"
      append-to-body
      >
      <el-form
        label-width="80px"
        ref="flowDialog"
        :model="flowDialog"
        :rules="flowDialogRules"
      >
        <el-row>
          <el-col :span="20">
            <el-form-item
              label="流程名称"
              prop="flowInfo.name"
              :rules="flowDialogRules.flowName"
            >
              <el-input
                v-model="flowDialog.flowInfo.name"
                placeholder="请输入流程名称"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item
              label="归属部门"
              prop="flowInfo.deptId"
              :rules="flowDialogRules.deptId"
            >
              <treeselect
                v-model="flowDialog.flowInfo.deptId"
                :options="deptOptions"
                :show-count="true"
                placeholder="请选择归属部门"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item
              label="流程标识"
              prop="flowInfo.flowIden"
              :rules="flowDialogRules.flowIden"
            >
              <el-input
                v-model="flowDialog.flowInfo.flowIden"
                placeholder="请输入流程标识"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="备注">
              <el-input
                v-model="flowDialog.flowInfo.flowInfo"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <div v-for="(item, index) in flowDialog.flowNodes" :key="(item, index)">
          <el-row>
            <el-col :span="20">
              <el-form-item
                :label="'节点' + (index + 1).toString()"
                :prop="`flowNodes.${index}.name`"
                :rules="flowDialogRules.nodeName"
              >
                <el-input
                  v-model="item.name"
                  placeholder="请输入节点名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item
                label="审核用户"
                :prop="`flowNodes.${index}.relatedUserId`"
                :rules="flowDialogRules.nodeUserId"
              >
                <el-select v-model="item.relatedUserId" placeholder="请选择">
                  <el-option
                    v-for="item0 in userList"
                    :key="item0.user_id"
                    :label="
                      item0.deptName +
                      ' | ' +
                      item0.user_name +
                      '-' +
                      item0.nick_name
                    "
                    :value="item0.user_id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="20">
              <el-form-item label="备注" prop="nodeInfo">
                <el-input
                  v-model="item.nodeInfo"
                  type="textarea"
                  placeholder="请输入节点备注"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-button type="primary" @click="handleAddNode(index+1)"
              >添加节点</el-button
            >
          </el-row>
          <el-divider></el-divider>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">发 布</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 表单选择抽屉 -->
    <el-drawer
      title="业务表单"
      :visible.sync="drawerVis"
      direction="rtl"
      size="50%"
    >
      <el-form
        label-width="80px"
        :rules="drawerRules"
        ref="drawer"
        :model="drawer"
      >
        <el-row>
          <el-col :span="15">
            <el-form-item label="选择部门" prop="deptId">
              <treeselect
                v-model="drawer.deptId"
                :options="deptOptions"
                :show-count="true"
                placeholder="根据部门选择表单"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleFormQuery"
              >搜索</el-button
            >
          </el-col>
        </el-row>
        <br />
        <div v-for="(item, index) in drawer.formList" :key="(item, index)">
          <el-card>
            <el-descriptions title="表单信息">
              <el-descriptions-item label="表单名">{{
                drawer.formList[index].formName
              }}</el-descriptions-item>
              <el-descriptions-item label="创建者名称">{{
                drawer.formList[index].userName
              }}</el-descriptions-item>
              <el-descriptions-item label="创建者昵称">{{
                drawer.formList[index].nickName
              }}</el-descriptions-item>
              <el-descriptions-item label="表单标签">
                <el-tag
                  v-for="(item0, index0) in drawer.formList[index].tagsArray"
                  :key="(item0, index0)"
                  size="small"
                  >{{ item0 }}</el-tag
                >&nbsp;
              </el-descriptions-item>
            </el-descriptions>
            <el-link style="color: blue" @click="handleAddFlow(index)"
              >建立流程</el-link
            >
          </el-card>
          <br />
        </div>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { nanoid } from "nanoid";
import { listDept } from "@/api/system/dept";
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
} from "@/api/system/user";
import {
  queryForm,
  getUserList,
  listFlow,
  publishFlow,
} from "@/api/flow/flowctr";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 审核节点用户数据
      userList: [],
      //流程数据列表
      flowList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      flowDialogVis: false,
      //是否显示抽屉
      drawerVis: false,
      //搜索表单的部门id
      drawer: { deptId: null, formList: [] },
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      flowDialog: { flowInfo: {}, flowNodes: [] },
      flowInfo: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      //流程状态选项
      flowStatusOptions: [
        { value: true, label: "启用" },
        { value: false, label: "禁用" },
      ],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        flowName: undefined, //流程名
        userName: undefined, //用户名
        deptIds: this.$store.state.user.deptids, //部门id数组
        flowIden: undefined, //流程英文标识
        flowStatus: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `流程名`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `流程标识`, visible: true },
        { key: 5, label: `创建时间`, visible: true },
        { key: 6, label: `状态`, visible: true },
      ],
      // 表单校验
      flowDialogRules: {
        flowName: {
          required: true,
          message: "流程名称不能为空",
          trigger: "blur",
        },
        deptId: {
          required: true,
          message: "归属部门不能为空",
          trigger: "blur",
        },
        flowIden: {
          required: true,
          message: "流程标识不能为空",
          trigger: "blur",
        },
        nodeName: {
          required: true,
          message: "节点名不能为空",
          trigger: "blur",
        },
        nodeUserId: {
          required: true,
          message: "审核用户不能为空",
          trigger: "blur",
        },
      },
      drawerRules: {
        deptId: {
          required: true,
          message: "部门选择不能为空",
          trigger: "blur",
        },
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    console.log(this.$store.state.user.token);
    this.getUserList();
    this.getTreeselect();
    this.getList();
    this.getConfigKey("sys.user.initPassword").then((response) => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    /** 查询流程列表 */
    getList() {
      this.loading = true;
      listFlow(this.addDateRange1(this.queryParams, this.dateRange)).then(
        (response) => {
          console.log(response);
          this.flowList = response.flowInfo;
          this.total = response.counts;
          this.loading = false;
        }
      );
    },
    /** 获取流程节点待选用户列表 */
    getUserList() {
      var params = {
        depts: this.$store.state.user.depts,
      };

      console.log(params);
      getUserList(params).then((response) => {
        console.log(response);
        this.userList = response.retMessage;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptIds = [data.id];
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.userName + '"用户吗？')
        .then(function () {
          return changeUserStatus(row.userId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.flowDialogVis = false;
    },
    // 表单重置
    reset() {
      this.flowDialog.flowInfo = {
        id: nanoid(), //流程Id
        name: "", //流程名
        userId: this.$store.state.user.id, //建立该流程的用户id
        deptId: null, //该流程隶属的部门id
        formId: "", //该流程关联的表单id
        nodes: 0, //该流程有的节点数
        flowInfo: "", //流程备注
        createTime: null,
        flowIden: null,
        status: true,
      };
      this.flowDialog.flowNodes = [];
      this.handleAddNode(0); //流程至少要一个节点
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 抽屉搜索按钮操作 */
    handleFormQuery() {
      this.$refs["drawer"].validate((valid) => {
        if (valid) {
          var params = {
            id: this.drawer.deptId,
          };
          console.log(params.id);
          queryForm(params).then((response) => {
            this.drawer.formList = response.departmentForm;
            this.drawer.formList.forEach((item) => {
              this.$set(item, "tagsArray", []);
              item.tagsArray = item.tags.split(",");
            });
            console.log(this.drawer.formList);
          });
        } else {
          return false;
        }
      });
    },
    /** 新建流程按钮操作 */
    handleAddFlow(i) {
      this.drawerVis = false;
      this.flowDialogVis = true;
      this.reset();
      this.flowDialog.flowInfo.formId = this.drawer.formList[i].id;
    },
    /** 新增审批节点操作 */
    handleAddNode(i) {
      var node = {
        id: nanoid(),
        name: undefined, //节点名
        flowId: this.flowDialog.flowInfo.id,
        orderId: ++this.flowDialog.flowInfo.nodes,
        last: false,
        relatedUserId: "", //关联该节点的用户
      };
      this.flowDialog.flowNodes.splice(i, 0, node);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    //重置抽屉数据
    resetDrawer() {
      this.drawer = { deptId: null, formList: [] };
      this.resetForm("drawer");
    },
    /** 新增按钮操作 */
    showFormList() {
      this.resetDrawer();
      this.drawerVis = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["flowDialog"].validate((valid) => {
        if (valid) {
          this.flowDialog.flowNodes[
            this.flowDialog.flowNodes.length - 1
          ].last = true;
          this.flowDialog.flowInfo.createTime = this.parseTime(new Date());
          var params = {
            flowInfo: this.flowDialog.flowInfo,
            flowNodes: this.flowDialog.flowNodes,
          };
          console.log(params);
          //发送请求，建立流程实例
          publishFlow(params).then((response) => {
            if (response.message == "flowIden重复！") {
              this.$message({
                message: "流程标识重复，请重新填写",
                type: "warning",
              });
            } else {
              this.$message({
                message: "发布流程成功",
                type: "success",
              });
              this.flowDialogVis = false;
              this.resetQuery();
            }
          });
        } else {
          console.log("error submit!!");
        }
      });
    },
  },
};
</script>
